package com.howie.shirojwt.controller;

import com.howie.shirojwt.dto.Meta;
import com.howie.shirojwt.dto.PermissionInfo;
import com.howie.shirojwt.dto.SourcePerm;
import com.howie.shirojwt.dto.UserPermiFreshFlag;
import com.howie.shirojwt.mapper.*;
import com.howie.shirojwt.model.*;
import com.howie.shirojwt.util.JWTUtil;
import org.apache.ibatis.reflection.ArrayUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created with IntelliJ IDEA

 * @Description admin角色权限controller

 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    final String permi_update_flag_fix="permi_update_flag_";
    private final UserDaoMapper userDaoMapper;
    private final ResultMap resultMap;
    @Autowired
    private  UserDomPermMapper userDomPermMapper;
    @Autowired
    private UserSourcePathMapper userSourcePathMapper;
    @Autowired
    private UserSourceActionMapper userSourceActionMapper;
    @Autowired
    private SourcePathMapper sourcePathMapper;
    @Autowired
    private SourceActionMapper sourceActionMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @Autowired
    public AdminController(UserDaoMapper userDaoMapper, ResultMap resultMap) {
        this.userDaoMapper = userDaoMapper;
        this.resultMap = resultMap;
    }

    @GetMapping("/getUser")
    @RequiresRoles("admin")
    public ResultMap getUser() {
        List<String> list = userDaoMapper.getUser();
        return resultMap.success().code(200).message(list);
    }

    /**
     * 封号操作
     */
    @PostMapping("/banUser")
    @RequiresRoles("admin")
    public ResultMap updatePassword(String username) {
        userDaoMapper.banUser(username);
        return resultMap.success().code(200).message("成功封号！");
    }

    /**
     * 用户的dom权限获取
     * @param username
     * @param url
     * @return
     */
    @RequiresRoles("admin")
    @GetMapping("/getDomPermi")
    public ResultMap getDomPermi(String username,String url) {
        UserDomPermExample example=new UserDomPermExample();
        UserDomPermExample.Criteria cri=example.createCriteria();
        cri.andUsernameEqualTo(username);
        if(!StringUtils.isEmpty(url)){
            cri.andUrlEqualTo(url);
        }


        List<UserDomPerm> list1= userDomPermMapper.selectByExample(example);

        List<UserDomPermBean> listRet=new ArrayList<>();
        for(UserDomPerm userDomPerm:list1){
            UserDomPermBean userDomPermBean=new UserDomPermBean();
            BeanUtils.copyProperties(userDomPerm,userDomPermBean);
            listRet.add(userDomPermBean);
        }
        return resultMap.success().code(200).message(listRet);
    }
    /**
     * 用户的soudom权限获取
     * @param username

     * @return
     */
    @RequiresRoles(logical = Logical.OR, value = {"user", "admin"})
    @GetMapping("/getUserAllPermi")
    public ResultMap getDomPermiAll( String username) {
        List<SourcePerm> sourcePermList=new ArrayList<>();

        init(username);

        UserSourcePathExample userSourceActionExample=new UserSourcePathExample();
        UserSourcePathExample.Criteria cri2=userSourceActionExample.createCriteria();
        cri2.andUsernameEqualTo(username);


        List<UserSourcePath> list2 =userSourcePathMapper.selectByExample(userSourceActionExample);
        for(UserSourcePath userSourcePath:list2){

            SourcePerm sourcePerm=new SourcePerm();
            BeanUtils.copyProperties(sourcePathMap.get(userSourcePath.getSourcePathId()),sourcePerm);
            sourcePerm.setHidden((sourcePathMap.get(userSourcePath.getSourcePathId()).getHidden()==0x00)?false:true);


            Meta meta=new Meta();
            sourcePerm.setMeta(meta);
            meta.setTitle(sourcePathMap.get(userSourcePath.getSourcePathId()).getTitle());
            Byte ka=sourcePathMap.get(userSourcePath.getSourcePathId()).getKeepAlive();
            Boolean kb= (ka == 0x00) ? false : true;
            meta.setKeepAlive(kb);
            if(sourceActionMap.containsKey(userSourcePath.getSourcePathId())){
                Map<Integer,SourceAction> tempmap=sourceActionMap.get(userSourcePath.getSourcePathId());
                for(Integer sourceactionId: tempmap.keySet()){
                    if(userActionMap.containsKey(sourceactionId)){
                        PermissionInfo permissionInfo=new PermissionInfo();
                        SourceAction sourceAction=tempmap.get(sourceactionId) ;
                        BeanUtils.copyProperties(sourceAction,permissionInfo);
                        permissionInfo.setDescribe(sourceAction.getDescription());
                        meta.getPermissionList().add(permissionInfo);

                    }
                }
            }
            int parentId=sourcePathMap.get(userSourcePath.getSourcePathId()).getParentId();
            if(0!=parentId){
                sourcePerm.setChildren(null);
            }else{
                if(sourcePathKidsMap.containsKey(userSourcePath.getSourcePathId())) {

                    sourcePerm.setChildren(kids(sourcePathKidsMap.get(userSourcePath.getSourcePathId()),list2));
                }

                sourcePermList.add(sourcePerm);
            }

        }



        return resultMap.success().code(200).message(null).result(sourcePermList);
    }

    public List<SourcePerm> kids(Set<SourcePath> sourcePaths,List<UserSourcePath> allUserSourcePaths){
        List<SourcePerm> kids = new ArrayList<>();

        for(UserSourcePath userSourcePath:allUserSourcePaths) {


            for (SourcePath sourcePath : sourcePaths) {
                if( userSourcePath.getSourcePathId().intValue()==sourcePath.getId().intValue()) {
                    SourcePerm sourcePerm = new SourcePerm();
                    BeanUtils.copyProperties(sourcePathMap.get(userSourcePath.getSourcePathId()), sourcePerm);
                    sourcePerm.setHidden((sourcePathMap.get(userSourcePath.getSourcePathId()).getHidden()==0x00)?false:true);
                    Meta metakids = new Meta();
                    metakids.setTitle(sourcePath.getTitle());
                    Byte ka=sourcePath.getKeepAlive();
                    Boolean kb= (ka == 0x00) ? false : true;
                    metakids.setKeepAlive(kb);
                    if (sourceActionMap.containsKey(userSourcePath.getSourcePathId())) {
                        Map<Integer, SourceAction> tempmap = sourceActionMap.get(userSourcePath.getSourcePathId());
                        for (Integer sourceactionId : tempmap.keySet()) {
                            if (userActionMap.containsKey(sourceactionId)) {
                                PermissionInfo permissionInfo = new PermissionInfo();
                                SourceAction sourceAction = tempmap.get(sourceactionId);
                                BeanUtils.copyProperties(sourceAction, permissionInfo);
                                permissionInfo.setDescribe(sourceAction.getDescription());
                                metakids.getPermissionList().add(permissionInfo);

                            }
                        }
                    }
                    sourcePerm.setMeta(metakids);
                    kids.add(sourcePerm);
                }
            }
        }
        return kids;
    }

    public void init(String username){

        /**
         * <sourcepathId,SourcePath>
         */
         sourcePathMap=new LinkedHashMap<>();
        /**
         * <sourcepathId,SourcePath>
         */
         sourcePathRootMap=new LinkedHashMap<>();
        /**
         * <parentId,SourcePath>
         */
         sourcePathKidsMap=new LinkedHashMap<>();

        /**
         * <sourcepathId,hashMap<SourceAcitonId,SourceAction></>>
         */
         sourceActionMap=new LinkedHashMap<>();
        /**
         * <SourceActionId,SourcePath>
         */
         userActionMap=new LinkedHashMap<>();

        SourcePathExample sourcePathExample=new SourcePathExample();
        SourcePathExample.Criteria sourcePathExampleCriteria=sourcePathExample.createCriteria();

        List<SourcePath> list =sourcePathMapper.selectByExample(sourcePathExample);
        for(SourcePath obj: list){
            sourcePathMap.put(obj.getId(),obj);
            if(obj.getParentId()==0){
                sourcePathRootMap.put(obj.getId(),obj);
            }else{
                if(sourcePathKidsMap.containsKey(obj.getParentId())){
                    sourcePathKidsMap.get(obj.getParentId()).add(obj);
                }else{
                    Set<SourcePath> listaa=new HashSet<>();
                    listaa.add(obj);
                    sourcePathKidsMap.put(obj.getParentId(),listaa);
                }
            }

        }


        SourceActionExample sourceActionExample=new SourceActionExample();
        SourceActionExample.Criteria a1=sourceActionExample.createCriteria();;

        List<SourceAction> listAction =sourceActionMapper.selectByExample(sourceActionExample);
        for(SourceAction obj: listAction){
            if(sourceActionMap.containsKey(obj.getSourceId())) {
                sourceActionMap.get(obj.getSourceId()).put(obj.getId(), obj);
            }else{
                Map<Integer,SourceAction> amp=new LinkedHashMap<>();
                sourceActionMap.put(obj.getSourceId(),amp);
                sourceActionMap.get(obj.getSourceId()).put(obj.getId(), obj);
            }
        }



        UserSourceActionExample example=new UserSourceActionExample();
        UserSourceActionExample.Criteria cri=example.createCriteria();
        cri.andUsernameEqualTo(username);

        List<UserSourceAction> list1 =userSourceActionMapper.selectByExample(example);
        for(UserSourceAction obj: list1){
            userActionMap.put(obj.getSourceActionId(),obj);
        }

    }

    /**
     * 用户的权限是否发生了更改
     * @param username

     * @return
     */
    @RequiresRoles(logical = Logical.OR, value = {"user", "admin"})
    @GetMapping("/getIsUserPerMiFresh")
    public ResultMap getIsUserPerMiFresh( String username) {
        UserPermiFreshFlag userPermiFreshFlag=new UserPermiFreshFlag();
        String v =stringRedisTemplate.opsForValue().get(permi_update_flag_fix+username);
        if(!StringUtils.isEmpty(v)){
            userPermiFreshFlag.setFresh(true);
        }
        return resultMap.success().code(200).message(null).result(userPermiFreshFlag);

    }

    /**
     * 更改用户权限
     * @param username
     * @return
     */
    @PostMapping("/updateUserPermi")
    @RequiresRoles(logical = Logical.OR, value = {"user", "admin"})
    public ResultMap updateUserPermi(@RequestParam("username") String username) {

        /**
         * 更改用户权限操作
         */
        if(!StringUtils.isEmpty(username)) {
            stringRedisTemplate.opsForValue().set(permi_update_flag_fix + username, username);
        }
        return resultMap.success().code(200).message("ok").result("ok");

    }


    /**
     * <sourcepathId,SourcePath> 存储所有的pathId到sourcepath的数据
     */
    public  Map<Integer,SourcePath>  sourcePathMap=new LinkedHashMap<>();
    /**
     * <sourcepathId,SourcePath>
     *     存储第一级pathId到sourcepath的数据
     */
    public  Map<Integer,SourcePath>  sourcePathRootMap=new LinkedHashMap<>();
    /**
     * <parentId,SourcePath>
     *     存储第二级parentId 到Set<SourcePath>
     */
    public  Map<Integer,Set<SourcePath>>  sourcePathKidsMap=new LinkedHashMap<>();

    /**
     * <sourcepathId,hashMap<SourceAcitonId,SourceAction></>>
     * 存储所有的
     */
    public   Map<Integer,Map<Integer,SourceAction>> sourceActionMap=new LinkedHashMap<>();
    /**
     * <SourceActionId,SourcePath>
     *     存储某个用户的
     */
    public   Map<Integer,UserSourceAction> userActionMap=new LinkedHashMap<>();


}
